<template>
	<view class="empire-timestamp">
		<view class="bg-red">{{ hour }}</view>
		<text>&nbsp;{{ separator }}&nbsp;</text>
		<view class="bg-red">{{ minute }}</view>
		<text>&nbsp;{{ separator }}&nbsp;</text>
		<view class="bg-red">{{ second }}</view>
	</view>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
const props = defineProps({
	timestamp: {
		type: String,
		required: true
	},
	separator: {
		type: String,
		default: ':'
	}
});
const timeId = ref();

const hour = ref();
const minute = ref();
const second = ref();
const millisecond = ref();
onMounted(() => {
	timeId.value = setInterval(() => createTimestamp(), 1000);
});
onUnmounted(() => {
	clearInterval(timeId);
	timeId.value = null;
});

function createTimestamp() {
	const [hour1, minute1, second1] = props.timestamp?.split(props.separator) || [];
	millisecond.value = millisecond.value || +hour1 * 3600000 + +minute1 * 60000 + +second1 * 1000;
	millisecond.value -= 1000;
	const hour2 = millisecond.value / 3600000;
	hour.value = `${compareTo10(Math.floor(hour2))}`;
	const point_m = `${hour2}`.indexOf('.');
	const minute2 = hour2 && point_m !== -1 ? +`${hour2}`.slice(point_m) * 60 : 0;
	minute.value = `${compareTo10(Math.floor(minute2))}`;
	const point_s = `${minute2}`.indexOf('.');
	second.value =
		minute2 && point_s !== -1
			? compareTo10(Math.round(+`${minute2}`.slice(point_s) * 60)) + ''
			: '00';
}

function compareTo10(value) {
	return value && value >= 10 ? `${value}` : `0${value}` || '00';
}
</script>

<style lang="scss" scoped>
.empire-timestamp {
	display: inline-flex;
	align-items: center;
	justify-content: center;
}
.bg-red {
	width: 44rpx;
	height: 40rpx;
	line-height: 40rpx;
	text-align: center;
	background-color: #ee0c0c;
	border-radius: 4rpx;
	color: #fff;
}
</style>
